

// 使用poll实现多路转接
#include <iostream>
#include <memory>
#include <sys/epoll.h>
#include <unistd.h>
#include <algorithm>
#include "Socket.hpp"

using namespace SocketModule;

class EpollServer
{
    const static int defaultfd = -1;
    const static int size = 4096;

public:
    EpollServer(int port) : _listensock(std::make_unique<TcpSocket>()), _isrunning(false)
    {
        _listensock->BuildTcpSocketMethod(port);
        // 创建epoll模型
        _epfd = epoll_create(256);
        if (_epfd < 0)
        {
            LOG(LogLevel::ERROR) << "epoll create error";
            exit(1);
        }
        LOG(LogLevel::INFO) << "epoll create success:" << _epfd;

        // 将listensockfd设置到内核中
        struct epoll_event ev;
        ev.data.fd = _listensock->Fd();
        ev.events = EPOLLIN;

        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, _listensock->Fd(), &ev);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "add listensockfd error";
            exit(2);
        }
    }
    void start()
    {
        int timeout = -1;
        _isrunning = true;
        while (_isrunning)
        {
            int n = epoll_wait(_epfd, _revs, size, timeout);
            switch (n)
            {
            case -1:
                LOG(LogLevel::ERROR) << "epoll error";
                break;
            case 0:
                LOG(LogLevel::INFO) << "time out...";
                break;
            default:
                // LOG(LogLevel::DEBUG) << "有事件就绪了...";
                Dispatcher(n); // n代表就绪的文件描述符的个数
                break;
            }
        }
        _isrunning = false;
    }
    // 事件派发器
    void Dispatcher(int rnum)
    {
        for (int i = 0; i < rnum; i++)
        {
            int sockfd = _revs[i].data.fd;
            uint32_t event = _revs[i].events;
            if (sockfd == _listensock->Fd())
            {
                Accepter();
            }
            else
            {
                Recver(sockfd);
            }
        }
    }
    // 链接获取
    void Accepter()
    {
        InetAddr client;
        int sockfd = _listensock->Accept(&client);
        if (sockfd < 0)
        {
            std::cerr << "accept error" << std::endl;
            return;
        }
        // 管理新连接
        struct epoll_event ev;
        ev.events = EPOLLIN;
        ev.data.fd = sockfd;

        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, sockfd, &ev);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "add sockfd error";
            return;
        }
        else
        {
            LOG(LogLevel::INFO) << "add sockfd success";
        }
    }
    // IO处理
    void Recver(int sockfd)
    {
        char buffer[1024];
        ssize_t n = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client say@:" << buffer << std::endl;
        }
        else if (n == 0)
        {
            std::cout << "client quit..." << std::endl;
            int m = epoll_ctl(_epfd, EPOLL_CTL_DEL, sockfd, nullptr);
            if (m > 0)
            {
                LOG(LogLevel::INFO) << "remove sockfd succsess";
            }
            close(sockfd);
        }
        else
        {
            LOG(LogLevel::ERROR) << "recv error";
            int m = epoll_ctl(_epfd, EPOLL_CTL_DEL, sockfd, nullptr);
            if (m > 0)
            {
                LOG(LogLevel::INFO) << "remove sockfd success";
            }
            close(sockfd);
        }
    }
    void stop()
    {
        _isrunning = false;
    }
    ~EpollServer()
    {
        _listensock->Close();
        if (_epfd > 0)
            close(_epfd);
    }

private:
    std::unique_ptr<Socket> _listensock;
    bool _isrunning;

    int _epfd;
    struct epoll_event _revs[size];
};
